<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * App\Models\Auth
 *
 * @property int $id
 * @property string $name
 * @property int $pid
 * @property string $url
 * @method static \Illuminate\Database\Eloquent\Builder|Auth newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Auth newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Auth query()
 * @method static \Illuminate\Database\Eloquent\Builder|Auth whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Auth whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Auth wherePid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Auth whereUrl($value)
 * @mixin \Eloquent
 */
class Budget extends Model
{
    protected $table = 'budget';

    /**
     * 获取当月预算
     * @param int $year 年
     * @param int $month 月
     * @param int $user_id 用户id
     * @return float 预算
     */
    public static function getBudgeByYearMonth(int $year, int $month, int $user_id): float
    {
        $budget = self::where('year', $year)
            ->where('month', $month)
            ->where('user_id', $user_id)
            ->where('soft_del', 1)
            ->value('budget');
        if (empty($budget)) {
            $budget = 0.00;
        }
        return number_format($budget, 2, '.', '');
    }

    /**
     * 设置预算方法
     * @param int $year
     * @param int $month
     * @param float $money
     * @param int $user_id
     * @return bool
     */
    public static function setBudgeByYearMonth(int $year, int $month, float $money, int $user_id): bool
    {
        $timestamp = now();
        $rs = self::upsert(
        // 需要写入或者更新的数据
            [
                ['user_id' => $user_id, 'year' => $year, 'month' => $month, 'budget' => $month, 'create_time' => $timestamp, 'update_time' => $timestamp]
            ],
            // 查询标识
            [
                'user_id', 'year', 'month'
            ],
            // 查询到之后的更新字段
            ['budget', 'update_time']
        );
        return (bool)$rs;
    }


}
